package com.ls.herostory.channel.handler;

import com.google.protobuf.Message;
import com.ls.herostory.msg.GameMsgProtocol.MsgCode;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GameMsgDecoder extends ChannelInboundHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(GameMsgDecoder.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(!(msg instanceof BinaryWebSocketFrame)){
            return;
        }

        BinaryWebSocketFrame frame = (BinaryWebSocketFrame)msg;
        ByteBuf buf = frame.content();

        // 消息内容
        short length = buf.readShort();
        short msgCodeValue = buf.readShort();
        byte[] body = new byte[buf.readableBytes()];
        buf.readBytes(body);

        // 消息类型
        MsgCode msgCode = MsgCode.forNumber(msgCodeValue);

        // 消息解析器
        Message.Builder msgBuilder = GameMsgRecognizer.getMsgBuilder(msgCode);
        if(msgBuilder == null){
            logger.error("没有找到匹配消息解码器：msgCode = {}", msgCode);
            return;
        }

        // 解析消息
        Message cmd = msgBuilder.mergeFrom(body).build();

        if(cmd != null){
            ctx.fireChannelRead(cmd);
        }
    }


}
